<template>
  <div>
    <!-- <h3>{{ $t('State') }}</h3> -->
    <div ref="devicesState" class="chart"></div>
  </div>
</template>
<script>
  import {
    codeByType,
  } from '@/views/device/common'
  const constPower = 0.01
  const defaultStateFn = function (device, json) {
    return device.online == true && json !== null ? 1 : 0
  }

  import socketAPI from "@/api/socket/socket";
  import * as echarts from 'echarts/core'
  import {
    TitleComponent,
    LegendComponent
  } from 'echarts/components';
  import {
    PieChart
  } from 'echarts/charts';
  import {
    LabelLayout
  } from 'echarts/features';
  import {
    CanvasRenderer
  } from 'echarts/renderers';

  echarts.use([
    PieChart, TitleComponent, LegendComponent, LabelLayout, CanvasRenderer
  ])

  export default {
    name: 'ModuleChart',
    props: {
      devices: {
        default () {
          return []
        }
      }
    },
    data() {
      const vm = this
      return {
        optionModules: {
          title: {
            bottom: -5,
            left: 'center',
            textStyle: {
              //文字颜色
              color: '#262626',
              //字体风格,'normal','italic','oblique'
              fontStyle: 'bold',
              //字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
              fontWeight: 'normal',
              //字体系列
              fontFamily: 'sans-serif',
              //字体大小
              fontSize: 16
            }
          },
          // legend: {
          //   show: true,
          //   data: [{
          //       name: '离线'
          //     },
          //     {
          //       name: '在线'
          //     },
          //     {
          //       name: '运行'
          //     },
          //   ]
          // },
          series: [{
            type: 'pie',
            radius: [20, 90],
            center: ['50%', '50%'],
            //roseType: 'radius',
            roseType: 'area',
            label: {
              show: true,
              color: '#262626',
              formatter: function (item) {
                var stateMes = ''
                if (item.data.state == 0) {
                  stateMes = vm.$t('Offline');
                } else if (item.data.state == 1) {
                  stateMes = vm.$t('Online');
                } else if (item.data.state == 2) {
                  stateMes = vm.$t('On')
                }
                return item.name + ' ' + stateMes;
              }
            },
            labelLine: { //指示线样式设置
              emphasis: {
                lineStyle: {
                  length: 2, //第一段指示线的长度
                  color: '#5fffff'
                },
              }

            },
            itemStyle: {
              borderRadius: 5,
              color: 'gray'
            },
            //color: ['#02e9ed', '#0342e1', '#02edc9', '#2ba4ea', '#3683f6', '#34affa', '#89a8ff', '#123ea1', '11939f', '#77adff'],
            data: [

            ]
          }]
        },
        chart: null,
        list: []
      }
    },
    watch: {
      devices(nv) {
        // if (!nv) {
        //   return
        // }
        this.list = [].concat(nv)
        this.updateChart(this.list)
      }
    },
    created() {
      this.list = [].concat(this.devices)
      socketAPI.addHandle(this.websocketReceive);
    },
    mounted() {
      this.$nextTick(this.createChart)
    },
    methods: {
      createModule(device, json, value, option) {
        const name = option ? option.name : null
        //const value = option ? option.value :null
        const stateFn = option ? option.stateFn : null
        const state = (stateFn || defaultStateFn)(device, json)
        var color = 'gray'
        if (state == 1) {
          color = '#37aabf';
        } else if (state == 2) {
          color = 'green';
        }
        const typeName = this.$t('dictionary.' + codeByType(device.type))
        return {
          name: name || device.name || typeName,
          value: value || 1,
          state: state,
          itemStyle: {
            color: color
          },
          label: {
            color: color
          }
        }
      },
      websocketReceive(data) {
        var isChanged = false
        for (var index in this.list) {
          if (this.list[index].code === data.code) {
            Object.assign(this.list[index], data)
            isChanged = true
            break
          }
        }
        if (isChanged) {
          this.updateChart(this.list)
        }
      },
      getModules(device) {
        const {
          createModule
        } = this
        const vm = this
        const address = device.code
        const name = device.name
        var stateJson = device.map
        if (address.includes("TH_RELAY")) {
          return createModule(device, stateJson, 1, {
            name: device.TH
          })
        }
        if (address.includes("PM_25")) {
          return createModule(device, stateJson, 1.1, {
            name: 'PM2.5'
          })
        }
        if (address.includes("TVOC_")) {
          return createModule(device, stateJson, 1.2, {
            name: 'tvoc'
          })
        }
        if (address.includes("IoT-AC-")) {
          return createModule(device, stateJson, 1.3)
        }
        if (address.includes("IoTLoRaLocker_")) {
          return createModule(device, stateJson, 1.3)
        }
        if (address.includes("CRT_RELAY_")) {
          return createModule(device, stateJson, 1.3)
        }
        if (address.includes("IR_CONTROL")) {
          return createModule(device, stateJson, 6)
        }
        if (address.includes("RF_RELAY")) {
          return createModule(device, stateJson, 5, {
            stateFn: function (device, json) {
              return defaultStateFn(device, json) > 0 ? device.curtainsState_ScreenIR == 'ON' ? 2 : 1 : 0;
            }
          })
        }
        if (address.includes("SCREEN_RELAY")) {
          return createModule(device, stateJson, 1, {
            stateFn: function (device, json) {
              return defaultStateFn(device, json) > 0 ? json.ENERGY !== undefined && json.ENERGY.Current >
                constPower ? 2 : 1 : 0;
            }
          })
        }
        if (address.includes("485_RELAY3_")) {
          var light1 = light2 = light3 = name;
          var names = name.split("|");
          if (names.length >= 3) {
            light1 = names[0];
            light2 = names[1];
            light3 = names[2];
          }
          return [
            createModule(device, stateJson, 1.3, {
              name: light1,
              stateFn: function (device, json) {
                return defaultStateFn(device, json) > 0 ? json.state1 > 0 ? 2 : 1 : 0;
              }
            }),
            createModule(device, stateJson, 1.4, {
              name: light2,
              stateFn: function (device, json) {
                return defaultStateFn(device, json) > 0 ? json.state2 > 0 ? 2 : 1 : 0;
              }
            }),
            createModule(device, stateJson, 1.5, {
              name: light3,
              stateFn: function (device, json) {
                return defaultStateFn(device, json) > 0 ? json.state3 > 0 ? 2 : 1 : 0;
              }
            })
          ]
        }
        if (address.includes("LIGHT_RELAY3_")) {
          var light1 = light2 = light3 = name;
          var names = name ? name.split("|") : [];
          if (names.length >= 3) {
            light1 = names[0];
            light2 = names[1];
            light3 = names[2];
          }
          return [
            createModule(device, stateJson, 1.3, {
              name: light1,
              stateFn: function (device, json) {
                return defaultStateFn(device, json) > 0 ? json.POWER1 == 'ON' ? 2 : 1 : 0;
              }
            }),
            createModule(device, stateJson, 1.4, {
              name: light2,
              stateFn: function (device, json) {
                return defaultStateFn(device, json) > 0 ? json.POWER2 == 'ON' ? 2 : 1 : 0;
              }
            }),
            createModule(device, stateJson, 1.5, {
              name: light3,
              stateFn: function (device, json) {
                return defaultStateFn(device, json) > 0 ? json.POWER3 == 'ON' ? 2 : 1 : 0;
              }
            })
          ]
        }
        if (address.startsWith("BleGate_")) {
          var arr = address.split("@");
          if (arr.length >= 3) {
            const type = parseInt(arr[1])
            switch (type) {
              case 2:
                var light1 = name,
                  light2 = name,
                  light3 = name;
                var names = name ? name.split("|") : [];
                if (names.length >= 3) {
                  light1 = names[0];
                  light2 = names[1];
                  light3 = names[2];
                }
                return [
                  createModule(device, stateJson, 1.3, {
                    name: light1,
                    stateFn: function (device, json) {
                      return defaultStateFn(device, json) > 0 ? json.Light1 == 'ON' ? 2 : 1 : 0;
                    }
                  }),
                  createModule(device, stateJson, 1.4, {
                    name: light2,
                    stateFn: function (device, json) {
                      return defaultStateFn(device, json) > 0 ? json.Light2 == 'ON' ? 2 : 1 : 0;
                    }
                  }),
                  createModule(device, stateJson, 1.5, {
                    name: light3,
                    stateFn: function (device, json) {
                      return defaultStateFn(device, json) > 0 ? json.Light3 == 'ON' ? 2 : 1 : 0;
                    }
                  })
                ]
              case 4:
                return createModule(device, stateJson, 1)
              case 6:
                return createModule(device, stateJson, 1, {
                  stateFn: function (device, json) {
                    return defaultStateFn(device, json) > 0 ? json.Current > (constPower * 1000) ? 2 : 1 : 0;
                  }
                })
              case 8:
                return createModule(device, stateJson, 1, {
                  name: vm.$t('device.Sensor') //todo special
                })
              case 11:
                return createModule(device, stateJson, 1)
              case 15:
                return createModule(device, stateJson, 6, {
                  stateFn: function (device, json) {
                    return defaultStateFn(device, json) > 0 ? json.Current > (constPower * 1000) ? 2 : 1 : 0;
                  }
                })
              case 16:
                return createModule(device, stateJson, 1, {
                  stateFn: function (device, json) {
                    return defaultStateFn(device, json) > 0 ? json.Current > (constPower * 1000) ? 2 : 1 : 0;
                  }
                })
              case 17:
                return createModule(device, stateJson, 1)
              case 100:
                return createModule(device, stateJson, 1)
            }
          }
        }
        return null
        //return createModule(device, stateJson, 1)
      },
      createChart() {
        this.chart = echarts.init(this.$refs.devicesState);
        this.chart.setOption(this.optionModules);
        this.updateChart(this.list)
      },
      updateChart(devices) {
        var dataModule = new Array();
        var moduleValue = 2
        const increment = 0.1
        for (var i = 0; i < devices.length; i++) {
          const device = devices[i]
          const modules = this.getModules(device)
          if (!modules) {
            continue
          }
          if (!(modules instanceof Array)) {
            modules.value = moduleValue
            dataModule.push(modules)
            moduleValue += increment
            continue
          }
          for (var j = 0; j < modules.length; j++) {
            const module = modules[j]
            module.value = moduleValue
            dataModule.push(module)
            moduleValue += increment
          }
        }
        if (dataModule.length === 0) {
          dataModule.push({
            name: this.$t('NoDevice'),
            value: 1,
            itemStyle: {
              color: 'gray'
            },
            label: {
              color: 'gray'
            }
          })
        }
        const vm = this
        this.chart.setOption({
          title: {
            text: vm.$t('device.DeviceStatus'),
            x: 'left',
            y: 'top',
            fontSize: 16,
            show: false
          },
          series: {
            data: dataModule
          }
        });
        // this.chart.resize()
        // const vm = this
        // this.$nextTick(function () {
        //   vm.chart.resize()
        // })
      }
    }
  }

</script>
<style scoped>
  .chart {
    min-width: 360px;
    width: 100%;
    height: 280px;
    margin: 0 auto;
  }

</style>
